const fs = require('fs')
const path = require('path')

const Controller = require('egg').Controller

class UploadsController extends Controller {
	async upload(){
		const { ctx, service } = this
		const uploadFile = ctx.request.files[0]
		const file = fs.readFileSync(uploadFile.filepath)
		const base64Str = Buffer.from(file, 'binary').toString('base64');
		const bufferData = Buffer.from(base64Str, 'base64');
		const uploadBasePath = path.join(__dirname, '../public/images')

		let fileName = uploadFile.filename.split('.')[0]
		const fileExtension = uploadFile.filename.split('.')[1]

		const timeSteamp = Date.now()
		fileName = fileName + timeSteamp + '.' + fileExtension

		// 将文件存到文件夹中
		try {
			await fs.writeFileSync(path.join(uploadBasePath, fileName), bufferData)
			await service.users.user.changeAvatar(fileName)
			ctx.body = ctx.success('上传头像成功', {
				fileName,
				url: '/public/images' + fileName
			})
		}catch (e){
				ctx.body = ctx.fail('上传文件失败', e)
		}
	}
}

module.exports = UploadsController
